package com.droidclaimcustomer.helper.service;

import java.io.File;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

import com.droidclaimcustomer.dto.UploadFileListDto;
import com.droidclaimcustomer.helper.asyntask.ProgressAsynTask;


public class FileUploadService<P, R> extends ProgressAsynTask<P, R> {
	public static final int HTTP_GET = 0;
	public static final int HTTP_POST = 1;
	
	private String serviceUrl;
	private ServiceMethod<R> serviceMethod;

	public FileUploadService() {
	}
	
	public void setServiceUrl(String serviceUrl) {
		this.serviceUrl = serviceUrl;
	}

	public void setWebServiceMethod(ServiceMethod<R> serviceMethod) {
		this.serviceMethod = serviceMethod;
	}
	
	@Override
	protected R performTaskInBackground(P... parameters) throws Exception {
		R result = null;

		String methodName = serviceMethod.getName();
		setTaskId(methodName);
		HttpRequestBase httpRequest;
		HttpPost httpPost = new HttpPost(serviceUrl);
		
		UploadFileListDto dto = (UploadFileListDto)serviceMethod.getParameterObject();
		
	    if(dto.getListFiles().size()>0)
	    {
	    	MultipartEntity reqEntity = new MultipartEntity();
	    	for (File file : dto.getListFiles()) {
	    		FileBody fileBody = new FileBody(file);
				reqEntity.addPart("stream",fileBody);
			}
	    	httpPost.setEntity(reqEntity);
	    }
	    httpRequest = httpPost;
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = httpclient.execute(httpRequest);
		
		String json = "";
		if(response.getEntity().getContentLength()>0){
			// stream reader object
	        Reader responseReader = new InputStreamReader(response.getEntity().getContent());
	        //create a buffer to fill if from reader
	        char[] buffer = new char[(int) response.getEntity().getContentLength()];
	        //fill the buffer by the help of reader
	        responseReader.read(buffer);
	        //close the reader streams
	        responseReader.close();
	
	        //for the employee json object
	        json = new String(buffer);
		}
				
		result = serviceMethod.mapResponse(json);

		return result;
	}

}